package ru.btabank.dom.xpath.parsers;

import java.util.ArrayList;

public abstract class Parser {

    private ArrayList tokens;

    private int position;

    private Lexer lexer;

    public Parser() {
        this.position = 0;
        this.tokens = new ArrayList(64);
        this.lexer = new Lexer();
    }

    public void parse(String string) throws ParsingException {
        this.position = 0;
        this.tokens.clear();
        this.lexer.tokenize(string);
        while (this.lexer.hasNext()) {
            this.tokens.add(this.lexer.next());
        }
    }

    protected void moveForward(int displacement) {
        position += displacement;
    }

    protected Token getToken(int position) {
        return (Token)this.tokens.get(position);
    }

    protected Token lookAhead(int displacement) {
        if ((position + displacement - 1) >= this.tokens.size())
            return new EndOfExpressionToken();
        return getToken(position + displacement - 1);
    }

    protected Token match(int tokenType) throws UnexpectedTokenException {
        if (lookAhead(1).getType() == tokenType) {
            moveForward(1);
            return lookAhead(0);
        } else
            throw new UnexpectedTokenException(lookAhead(1));
    }
}
